package com.ichifinga.airwave.shared;

import com.ichifinga.airwave.shared.entities.Phrase;
import android.graphics.Canvas;
import android.view.SurfaceHolder;

public class DisplayThread extends Thread 
{
    private SurfaceHolder _surfaceHolder;
    private boolean _runFlag = false;
    DisplayObject _displayObject;
    
    private boolean _nextFrame = false;
    private boolean _previousFrame = false;
    private boolean _firstFrame = false;
	
    public DisplayThread(SurfaceHolder surfaceHolder, boolean editMode, int width, int height,
    		Phrase phrase)
    {
    	_surfaceHolder = surfaceHolder;
    	
        _displayObject = new DisplayObject(editMode, width, height, phrase);        
    }
     
    public void setRunning(boolean run)
    {
        _runFlag = run;
    }
    
    @Override
    public void run()
    {
        Canvas c;
        
        while (_runFlag)
        {
            c = null;
            try {
               
                c = _surfaceHolder.lockCanvas(null);
                
                synchronized (_surfaceHolder)
                {	
                	if(_nextFrame)
                	{
                		NextFrame();
                	}
                	
                	if(_previousFrame)
                	{
                		PreviousFrame();
                	}
                	
                	if(_firstFrame)
                	{
                		FirstFrame();
                	}
                        	
                    _displayObject.Draw(c);
                }
            }
            finally
            {
                if (c != null)
                {
                    _surfaceHolder.unlockCanvasAndPost(c);
                }
            }
            try
            {
				sleep(10);//50
			}
            catch (InterruptedException e)
            {
				e.printStackTrace();
			}
        }
    }
    
    private void NextFrame()
    {
    	_nextFrame = false;
    	_displayObject.NextFrame();    	
    }
    
    private void PreviousFrame()
    {
    	_previousFrame = false;
    	_displayObject.PreviousFrame();
    }
    
    private void FirstFrame()
    {
    	_firstFrame = false;
    	_displayObject.FirstFrame();
    }
    
    public void SetNextFrame()
    {
    	_nextFrame = true;    	
    }
    
    public void SetPreviousFrame()
    {
    	_previousFrame = true;
    }
    
    public void SetFirstFrame()
    {
    	_firstFrame = true;
    }
}    
    
    


